package com.risenetsoft.elasticsearch.api;

import org.apache.lucene.index.Terms;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by Zhanggd on 2017/8/7.
 */
public class SearchApiTest {
    public static final String CLUSTER_NAME = "elasticsearch"; //实例名称
    private static final int PORT = 9300;  //端口
    private static final String IP = "192.168.190.104";
    private static Settings settings = Settings.builder()
            .put("cluster.name",CLUSTER_NAME)
            .put("client.transport.sniff",true)
            .put("client.transport.ping_timeout","120s")
            .build();

    private static TransportClient client;
    static {
        try {
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(IP), PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //search();

        //multiSearch();

        //aggregationSearch();

        terminateSearch();
    }
    /**
     * 查询指定的索引：可以是多个索引
     */
    public static void search(){
        SearchResponse response = client.prepareSearch("us", "gb")
                .setTypes("user", "tweet")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.termQuery("name", "Mary Jones"))
                .setFrom(0).setSize(60).setExplain(true)
                .get();
        SearchHits hits = response.getHits();
        Long total = hits.totalHits;
        System.out.println(total);
    }

    /**
     * 查询所有的索引
     */
    public static void searchAll(){
        SearchResponse response = client.prepareSearch().get();
    }

    /**
     * 使用Scroll API查询
     */
    public static void scroll(){
        TermQueryBuilder queryBuilder = QueryBuilders.termQuery("multi", "test");
        SearchRequestBuilder response = client.prepareSearch();
    }

    public static void multiSearch(){
        SearchRequestBuilder requestBuilder1 = client.prepareSearch()
                .setQuery(QueryBuilders.queryStringQuery("elasticsearch"))
                .setSize(1);

        SearchRequestBuilder requestBuilder2 = client.prepareSearch()
                .setQuery(QueryBuilders.matchQuery("name","kimchy")).setSize(1);

        MultiSearchResponse response = client.prepareMultiSearch()
                .add(requestBuilder1)
                .add(requestBuilder2)
                .get();

        long nbHits = 0;
        for(MultiSearchResponse.Item item:response.getResponses()){
            SearchResponse searchResponse = item.getResponse();
            nbHits += searchResponse.getHits().getTotalHits();
        }

    }

    /**
     * 聚合函数的使用
     */

    public static void aggregationSearch(){
        SearchResponse searchResponse = client.prepareSearch()
                .setQuery(QueryBuilders.matchAllQuery())
                .addAggregation(AggregationBuilders.terms("agg1").field("field"))
                .addAggregation(AggregationBuilders.dateHistogram("agg2")
                        .field("birth")
                        .dateHistogramInterval(DateHistogramInterval.DAY))
                .get();

        Terms terms =searchResponse.getAggregations().get("agg1");
        DateHistogramInterval agg2 = searchResponse.getAggregations().get("agg2");

    }

    /**
     * 设置每个分片最大收集文档的数量，当到达该数量后，查询将会终止
     */
    public static void terminateSearch(){
        SearchResponse searchResponse = client.prepareSearch("us", "gb")
                .setQuery(QueryBuilders.matchAllQuery())
                .setTerminateAfter(2)
                .get();

        //检查是否提前终止查询
        if (searchResponse.isTerminatedEarly()){
            System.out.println("查询提前终止");
        }
    }
}
